﻿using Finance.ErrorCode;
using Finance.Infrastructrue.Interface;
using Finance.API.Write.Application.Command.FinancialCategoryCommand;
using Finance.Domain;
using MediatR;
using System.DirectoryServices.Protocols;
using MySqlX.XDevAPI.Common;
using AutoMapper;
using System.Data;
using Finance.Infrastructrue.Implement;

namespace Finance.API.Write.Application.Hander.FinancialCategoryHander
{
    public class AddFinancialCategoryHander : IRequestHandler<AddFinancialCategoryCommand, APIResult<int>>
    {
        
        DatabaseContext Db;
        IBaseRepository<FinancialCategory> finRep;
        ILogger<AddFinancialCategoryHander> logger;
        IMapper mapper;

        public AddFinancialCategoryHander(DatabaseContext db, IBaseRepository<FinancialCategory> finRep, ILogger<AddFinancialCategoryHander> logger, IMapper mapper)
        {
            Db = db;
            this.finRep = finRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public  async Task<APIResult<int>> Handle(AddFinancialCategoryCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
                var financial = mapper.Map<FinancialCategory>(request);
                financial.IsDel=false;
                var m = await Db.SqlSugar.Insertable(financial).ExecuteCommandAsync();

                if (m > 0)
                {
                    result.Code = APIEnum.Ok;
                    result.Message = "财务类型财务类别添加成功";
                    result.Data = m;
                }
                else
                {
                    result.Code = APIEnum.Fail;
                    result.Message = "财务类型财务类别添加失败";
                    result.Data = m;
                }

                logger.LogInformation("财务类型财务类别添加成功");
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                
                logger.LogError("财务类型财务类别添加报错" + ex.Message);
                throw;
            }
            return await Task.FromResult(result);

        }
    }
}
